#include "ftpainter.h"
#include "configuration.h"

FTPainter::FTPainter(QPaintDevice *pd) :
    QPainter(pd)
{
    drawWaypoint = configuration->drawWaypoint();
    drawWaypointIcon = configuration->drawWaypointIcon();
    drawWaypointName = configuration->drawWaypointName();
}

void FTPainter::drawTrack(const GPS_track& track,
                          const QTransform& matrix,
                          const QRectF& visible_area)
{

    if ( !track.boundingRect().intersects( visible_area ) )
        return;

    const GPS_leg* leg;
    QList<int> leg_ids = track.listLegs();
    foreach ( int leg_id, leg_ids )
    {
        leg = track.leg( leg_id );
        if ( leg != NULL )
        {
            setPen( QPen( leg->color(), track.lineWidth() ) );
            int npts = leg->nPoints();
            QPointF pta, ptb;

            for ( int i = 0; i < npts; i++ )
            {
                if ( i == 0 )
                    pta = leg->quickPoint(i) * matrix;
                else
                {
                    ptb = leg->quickPoint(i) * matrix;
                    drawLine( pta, ptb );
                    pta = ptb;
                }
            }
        }
    }

    if ( drawWaypoint )
    {
        QList<int> waypoints_ids = track.listWaypoints();
        const GPS_waypoint* wp;
        foreach ( int waypoint_id, waypoints_ids )
        {
            wp = track.waypoint( waypoint_id );
            if ( wp != NULL )
            {
                setPen( QPen( QBrush(wp->color()), 0) );

                QPoint screenPt = (QPointF( wp->longitude(),
                                            wp->latitude()) * matrix).toPoint();

                // First draw the circle to match the waypoint
                drawRect( screenPt.x()-2, screenPt.y()-2, 4, 4 );

                if ( drawWaypointIcon )
                {
                    QPixmap pxm( ":/table/waypoint_to.png" );
                    drawPixmap( screenPt - QPoint( pxm.width(), pxm.height() ), pxm );
                }
                if ( drawWaypointName )
                    drawText( screenPt + QPoint( 5, 5), wp->name() );
            }
        }
    }
}

